let floatingButton; // 声明全局变量
let floatingWindow; // 悬浮窗元素
let circleLoader; // 转圈圈元素
let firstClick = true; // 跟踪是否是第一次点击
let returndata = ''
function createFloatingButton() {
    if (!floatingButton) {
        floatingButton = createButtonElement();
        document.body.appendChild(floatingButton);
        console.log('1')
        // 创建悬浮窗，并传递悬浮球作为参数
        floatingWindow = createFloatingWindow(floatingButton);
        document.body.appendChild(floatingWindow);

        // 创建转圈圈
        circleLoader = createCircleLoader();
        document.body.appendChild(circleLoader);

        // 创建蒙版
        const mask = createMask();
        document.body.appendChild(mask);
        suspensionBall('floatingButton', '#');
    }
}

function createButtonElement() {
    const button = document.createElement('div');
    button.id = 'floatingButton';
    button.style.cssText = `
        position: fixed;
        bottom: 100px;
        right: 100px;
        width: 50px;
        height: 50px;
        background-color: transparent;
        border-radius: 50%;
        display: flex;
        justify-content: center;
        align-items: center;
        cursor: pointer;
        box-shadow: 0 4px 6px rgba(139,0,0,0.3);
        z-index: 9999;
        transition: width 0.2s ease, height 0.2s ease;
    `;

    const iconImage = document.createElement('img');
    iconImage.src = chrome.runtime.getURL("icons/icon.png");
    iconImage.alt = "悬浮球";
    iconImage.style.paddingTop = '3px';
    iconImage.style.width = '30px';
    iconImage.style.height = '30px';
    button.appendChild(iconImage);
    return button;
}

function createFloatingWindow(floatingButton) {
    const window = document.createElement('div');
    window.id = 'floatingWindow';
    window.style.cssText = `
        position: fixed;
        width: 200px;
        height: 300px;
        max-height: 350px;
        background-color: white;
        border: 1px solid #ccc;
        box-shadow: 0 4px 6px rgba(0,0,0,0.1);
        display: none; /* 初始隐藏 */
        z-index: 9998;
        overflow-y: auto; /* 添加竖向滚动条 */
        padding: 10px;
        box-sizing: border-box;
        border-radius: 10px; /* 添加圆角 */
        text-align: center;
        scrollbar-width: thin; 
        scrollbar-color: #982020 transparent;
    `;
    console.log('2')
    // 更新悬浮窗位置，使悬浮窗的右下角与悬浮球的左上角对齐
    updateFloatingWindowPosition(floatingButton, window);
    return window;
}

function updateFloatingWindowPosition(floatingButton, floatingWindow) {
    // 悬浮窗口的宽度和高度
    var windowWidth = floatingWindow.offsetWidth;
    var windowHeight = floatingWindow.offsetHeight;

    // 悬浮球的当前位置
    var buttonRect = floatingButton.getBoundingClientRect();

    // 计算悬浮窗口的新位置，使悬浮窗口的右下角与悬浮球的左上角对齐
    var newLeft = buttonRect.left - windowWidth;
    var newTop = buttonRect.top - windowHeight;

    // 确保悬浮窗口的新位置不会超出屏幕边界
    newLeft = Math.max(newLeft, 0);
    newLeft = Math.min(newLeft, document.documentElement.clientWidth - windowWidth);
    newTop = Math.max(newTop, 0);
    newTop = Math.min(newTop, document.documentElement.clientHeight - windowHeight);

    // 设置悬浮窗口的新位置
    floatingWindow.style.left = newLeft + 'px';
    floatingWindow.style.top = newTop + 'px';

    // 清空 floatingWindow 的内容
    while (floatingWindow.firstChild) {
        floatingWindow.removeChild(floatingWindow.firstChild);
    }

    // 创建包含鉴别结果和重试的容器
    const titleContainer = document.createElement('div');
    titleContainer.style.display = 'flex';
    titleContainer.style.alignItems = 'center';
    titleContainer.style.justifyContent = 'center';
    titleContainer.style.color = '#982020';

    // 创建标题元素
    const titleDiv = document.createElement('div');
    titleDiv.style.fontSize = 'larger';
    titleDiv.style.fontWeight = 'bold';
    titleDiv.textContent = '鉴别结果';

    // 创建图标元素
    const iconImage = document.createElement('img');
    iconImage.src=''
    iconImage.style.width = '20px';
    iconImage.style.height = '20px';
    iconImage.style.marginLeft = '10px';
    iconImage.style.marginRight = '10px';
    iconImage.style.cursor = 'pointer';
    iconImage.style.color = 'black';
    iconImage.addEventListener('mouseover', function () {
        this.src=''
    });
    iconImage.addEventListener('mouseout', function () {
        this.src=''
    });
    // 处理 returnData
    let processedData = returndata;
    const falseInfoPattern = /虚假信息：/g;
    const truthPattern = /真相：/g;
    processedData = processedData.replace(falseInfoPattern, '\n<br><b>虚假信息：</b>');
    processedData = processedData.replace(truthPattern, '\n<br><b>真相：</b>');

    // 创建段落元素
    const paragraph = document.createElement('p');
    paragraph.style.textAlign = 'left';
    paragraph.innerHTML = processedData;

    var refreshText = document.createElement('span');
    refreshText.textContent = '重试';
    refreshText.style.cursor = 'pointer';
    refreshText.style.color = 'black';
    refreshText.addEventListener('mouseover', function () {
        this.style.color = '#982020';
    });
    refreshText.addEventListener('mouseout', function () {
        this.style.color = 'black';
    });
    let tooltip = null;

    refreshText.addEventListener('click', function () {
        firstClick = true;
        floatingWindow.style.display = 'none';
        toggleFloatingWindow();
    });
    iconImage.addEventListener('click', function () {
        firstClick = true;
        floatingWindow.style.display = 'none';
        toggleFloatingWindow();
    });

    // 将标题、图标和重试文本添加到容器
    titleContainer.appendChild(titleDiv);
    titleContainer.appendChild(iconImage);
    titleContainer.appendChild(refreshText);

    // 将容器和段落添加到 floatingWindow
    floatingWindow.appendChild(titleContainer);
    floatingWindow.appendChild(paragraph);
}

function createCircleLoader() {
    const circleLoaderElement = document.createElement('div');
    circleLoaderElement.className = 'circle-loader';
    circleLoaderElement.style.cssText = `
        position: fixed;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        display: none; /* 初始隐藏 */
    `;
    for (let i = 1; i <= 8; i++) {
        const div = document.createElement('div');
        div.style.cssText = `
            height: 10px;
            width: 10px;
            background-color: #982020;
            border-radius: 50%;
            position: absolute;
            animation: opaque 0.8s ease-in-out infinite both;
        `;
        if (i > 1) {
            div.style.animationDelay = `${(i - 1) * 0.1}s`;
        }
        const positions = [
            { top: '-25px', left: '0' },
            { top: '-17px', left: '17px' },
            { top: '0', left: '25px' },
            { top: '17px', left: '17px' },
            { top: '25px', left: '0' },
            { top: '17px', left: '-17px' },
            { top: '0', left: '-25px' },
            { top: '-17px', left: '-17px' }
        ];
        div.style.top = positions[i - 1].top;
        div.style.left = positions[i - 1].left;
        circleLoaderElement.appendChild(div);
    }
    return circleLoaderElement;
}

// 定义关键帧动画
const style = document.createElement('style');
style.type = 'text/css';
style.innerHTML = `
@keyframes opaque {
    from {
        opacity: 1;
    }
    50% {
        opacity: 0.2;
    }
    to {
        opacity: 1;
    }
}
`;
document.head.appendChild(style);

// 创建蒙版元素
function createMask() {
    const maskElement = document.createElement('div');
    maskElement.id = 'mask';
    maskElement.style.cssText = `
        display: none;
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background-color: rgba(0, 0, 0, 0.3);
        z-index: 9999;
    `;
    document.body.appendChild(maskElement);
    return maskElement;
}
async function toggleFloatingWindow() {
    if (floatingWindow.style.display === 'none') {
        if (firstClick) {
            firstClick = false; // 标记已显示过转圈圈
            circleLoader.style.display = 'block'; // 显示转圈圈
            document.getElementById('mask').style.display = 'block'; // 显示蒙版

            //获取正文
            const articleElement = document.createElement('div');
            articleElement.innerHTML = document.documentElement.outerHTML;

            const paragraphs = articleElement.querySelectorAll('p');
            let chineseText = '';

            paragraphs.forEach((paragraph) => {
                chineseText += paragraph.textContent;
            });

            console.log(chineseText);
            let s = chineseText;
            //'http://127.0.0.1:5000/process_content'
            await fetch('https://perfxcloud-lqsqomidpq.cn-hangzhou.fcapp.run/process_content', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({content: s})
            })
                .then(response => response.text())
                .then(data => {
                    console.log(data);
                    returndata = data;
                })
                .catch(error => {
                    console.error('Error:', error);
                });

                circleLoader.style.display = 'none'; // 隐藏转圈圈
                document.getElementById('mask').style.display = 'none'; // 隐藏蒙版
                floatingWindow.style.display = 'block'; // 显示悬浮窗
                updateFloatingWindowPosition(floatingButton, floatingWindow); // 更新悬浮窗位置

        } else {
            // 直接设置悬浮窗的位置并显示
            floatingWindow.style.display = 'block';
        }
    } else {
        floatingWindow.style.display = 'none';
    }
}

function suspensionBall(dragId, dragLink) {
    var startEvt, moveEvt, endEvt;
    if ('ontouchstart' in window) {
        startEvt = 'touchstart';
        moveEvt = 'touchmove';
        endEvt = 'touchend';
    } else {
        startEvt = 'mousedown';
        moveEvt = 'mousemove';
        endEvt = 'mouseup';
    }
    var drag = document.getElementById(dragId); // 初始化 drag 变量
    drag.style.position = 'flexed';
    drag.style.cursor = 'pointer';
    var isClick = true;
    var disX, disY, left, top, starX, starY;

    drag.addEventListener(startEvt, function(e) {
        e.preventDefault();
        var e = e || window.event;
        isClick = true;
        starX = e.touches ? e.touches[0].clientX : e.clientX;
        starY = e.touches ? e.touches[0].clientY : e.clientY;
        disX = starX - drag.offsetLeft;
        disY = starY - drag.offsetTop;
        document.addEventListener(moveEvt, moveFun);
        document.addEventListener(endEvt, endFun);
        drag.style.width = "60px";
        drag.style.height = "60px";
    });
    function moveFun(e) {
        var e = e || window.event;
        isClick = false;
        left = (e.touches ? e.touches[0].clientX : e.clientX) - disX;
        top = (e.touches ? e.touches[0].clientY : e.clientY) - disY;
        if (left < 0) {
            left = 0;
        } else if (left > document.documentElement.clientWidth - drag.offsetWidth) {
            left = document.documentElement.clientWidth - drag.offsetWidth;
        }
        if (top < 0) {
            top = 0;
        } else if (top > document.documentElement.clientHeight - drag.offsetHeight) {
            top = document.documentElement.clientHeight - drag.offsetHeight;
        }
        drag.style.left = left + 'px';
        drag.style.top = top + 'px';

        // 更新悬浮窗位置，使悬浮窗的右下角与悬浮球的左上角对齐
        if (floatingWindow) {
            // 悬浮窗口的宽度和高度
            var windowWidth = floatingWindow.offsetWidth;
            var windowHeight = floatingWindow.offsetHeight;

            // 计算悬浮窗口的新位置，使悬浮窗口的右下角与悬浮球的左上角对齐
            var newLeft = left - windowWidth;
            var newTop = top - windowHeight;

            // 确保悬浮窗口的新位置不会超出屏幕边界
            newLeft = Math.max(newLeft, 0);
            newLeft = Math.min(newLeft, document.documentElement.clientWidth - windowWidth);
            newTop = Math.max(newTop, 0);
            newTop = Math.min(newTop, document.documentElement.clientHeight - windowHeight);

            // 设置悬浮窗口的新位置
            floatingWindow.style.left = newLeft + 'px';
            floatingWindow.style.top = newTop + 'px';
        }

    }

   function endFun(e) {
        document.removeEventListener(moveEvt, moveFun);
        document.removeEventListener(endEvt, endFun);
        var deltaX = (e.touches ? e.touches[0].clientX : e.clientX) - starX;
        var deltaY = (e.touches ? e.touches[0].clientY : e.clientY) - starY;
        if (Math.abs(deltaX) < 5 && Math.abs(deltaY) < 5) {
            drag.style.width = "50px";
            drag.style.height = "50px";
            toggleFloatingWindow();
            // 更新悬浮窗位置，使悬浮窗的右下角与悬浮球的左上角对齐
            if (floatingWindow) {
                // 悬浮窗口的宽度和高度
                var windowWidth = floatingWindow.offsetWidth;
                var windowHeight = floatingWindow.offsetHeight;

                // 计算悬浮窗口的新位置，使悬浮窗口的右下角与悬浮球的左上角对齐
                var newLeft = left - windowWidth;
                var newTop = top - windowHeight;

                // 确保悬浮窗口的新位置不会超出屏幕边界
                newLeft = Math.max(newLeft, 0);
                newLeft = Math.min(newLeft, document.documentElement.clientWidth - windowWidth);
                newTop = Math.max(newTop, 0);
                newTop = Math.min(newTop, document.documentElement.clientHeight - windowHeight);

                // 设置悬浮窗口的新位置
                floatingWindow.style.left = newLeft + 'px';
                floatingWindow.style.top = newTop + 'px';
            }
        } else {
            drag.style.width = "50px";
            drag.style.height = "50px";
        }
        isClick = true;
    }
}

function removeElement(element) {
    if (element && document.body.contains(element)) {
        document.body.removeChild(element);
    }
}

function removeFloatingButton() {
    if (floatingButton && document.body.contains(floatingButton)) {
        document.body.removeChild(floatingButton);
        floatingButton = null;
    }
}
function removeFloatingWindow() {
    if (floatingWindow && document.body.contains(floatingWindow)) {
        document.body.removeChild(floatingWindow);
        floatingWindow = null;
    }
}
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
    if (request.action === 'show') {
        createFloatingButton();
        localStorage.setItem('floatingButtonVisible', true);
        localStorage.setItem('floatingWindow',true);
    } else if (request.action === 'hide') {
        removeFloatingButton();
        removeFloatingWindow();
        localStorage.setItem('floatingButtonVisible', false);
        localStorage.setItem('floatingWindow', false);
    }
    else if(request.action==='endFun'){
        firstClick = true;
        floatingWindow.style.display = 'none'
        toggleFloatingWindow();
    }
    return true; // 确保异步响应
});

window.onload = function() {
    const isVisible = localStorage.getItem('floatingButtonVisible') === 'true';
    if (isVisible) {
        createFloatingButton();
    }
};